package com.cloudcross.ssp.web.back.main;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.Config;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Md5Tool;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.*;
import com.cloudcross.ssp.service.*;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 客户账号管理 修改人：wuqiang.du 修改时间：2016-03-14
 * 客户端账号管理，即后台管理员及具有创建账号权限的人登入系统给运营商和广告主代理商创建账号，以便他们登入运营商系统或广告主系统
 */
@Controller
@RequestMapping("/back/main/client-account")
public class ClientAccountController extends SimpleController {

    @Autowired
    protected IAccountService           accountService;
    @Autowired
    protected IUserLoginService         userLoginService;
    @Autowired
    protected IOperatorService          operatorService;
    @Autowired
    protected IAdvAgentService          advAgentService;
    @Autowired
    private FreemarkerTemplateProcessor templateProcessor;
    @Autowired
    protected IRolesService             roleService;
    @Autowired
    protected ICorrelationService       correlationService;
    @Autowired
    private IResourcesService           resourcesService;
    @Autowired
    Config                              config;

    /**
     * 重定向
     * 
     * @return 目标url
     */
    @RequestMapping
    public String index() {
        return redirect(page("list"));
    }

    /**
     * 后台客户账号管理
     * 
     * @param model
     * @param page
     * @param sysType 2--媒体 3--需求方
     * @param searchValue
     * @return 后台客户账号管理：显示媒体账号或需求方账号 媒体账号sys_type=2 and operator_id>0
     *         代理商账号sys_type=3 and agent_id >0 and advertiser_id = 0
     */
    @RequestMapping("list")
    public String list(Model model, @RequestParam(defaultValue = "1") int page,
                       @RequestParam(defaultValue = "0") Long sysType, String searchValue) {
        Map<String, Object> condition = new HashMap<String, Object>();

        if (sysType != null && sysType != 0) {
            condition.put("sysType", sysType);
        }
        if (StringUtils.isNotBlank(searchValue)) {
            condition.put("searchVal", "%" + searchValue + "%");
        }
        model.addAttribute("searchValue", searchValue);

        int totalRow = accountService.queryClientAccountCountByCondition(condition);
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<ClientAccount> clientAccountsList = accountService.queryClientAccountByCondition(condition, pager);

        //循环得到每个客户账号的最后登录时间！
        for (ClientAccount ca : clientAccountsList) {
            UserLogin login = userLoginService.queryUserLoginById(ca.getId());
            if (login == null) {
                continue;
            }
            ca.setLoginTime(login.getLoginTime());
        }
        model.addAttribute("pager", pager);
        model.addAttribute("sysType", sysType);
        model.addAttribute("clientAccountsList", clientAccountsList);
        return page("list");
    }

    /**
     * 到创建账号页面
     * 
     * @param model
     * @param sysType
     * @return sysType 0（全部），2（媒体），3（需求方）
     */
    @RequestMapping("/create")
    public String create(Model model, @RequestParam(defaultValue = "0") Long sysType) {
        if (sysType == 0) {//若点击创建账号按钮时，账号类型为全部，则默认为到创建媒体界面
            sysType = new Long(2);
        }
        model.addAttribute("sysType", sysType);
        return page("create");
    }

    /**
     * 客户端账号管理编辑页面
     * 
     * @param model
     * @param accountId
     * @return 注意是媒体编辑页面还是运营商编辑页面，根据sysType的值来判断
     */
    @RequestMapping("/edit")
    public String edit(Model model, @RequestParam Long accountId) {
        //当前登录用户信息	
        Account account = accountService.queryAccountById(accountId);
        ClientAccount clientAccount = null;
        String authority = "";
        if (account.getSysType() == 3) {
            //是代理商账号的编辑
            AdvAgent advAgent = advAgentService.findById(account.getAgentId());
            //把accout 和 advAgent封装成clientAccount对象
            clientAccount = new ClientAccount();
            clientAccount.setId(account.getId());
            clientAccount.setSysType(account.getSysType());
            clientAccount.setType(account.getType());
            clientAccount.setAccountName(account.getAccountName());
            clientAccount.setPassword(account.getPassword());
            clientAccount.setLinkMan(advAgent.getContacts());
            clientAccount.setMobilePhone(advAgent.getMobile());
            clientAccount.setTel(advAgent.getTel());
            clientAccount.setCompanyName(advAgent.getName());
            clientAccount.setHomePage(advAgent.getHomePage());
            clientAccount.setAddress(advAgent.getAddress());
            clientAccount.setEmail(advAgent.getEmail());
            clientAccount.setZip(advAgent.getZip());//邮编
            clientAccount.setTitle(advAgent.getTitle());
            clientAccount.setAgentId(advAgent.getId());
            clientAccount.setStatus(Integer.parseInt(account.getState()));

        }
        if (account.getSysType() == 2) {
            //是媒体账号的编辑
            Operator operator = operatorService.findById(account.getOperatorId());
            clientAccount = new ClientAccount();
            clientAccount.setId(account.getId());
            clientAccount.setSysType(account.getSysType());
            clientAccount.setType(account.getType());
            clientAccount.setAccountName(account.getAccountName());
            clientAccount.setPassword(account.getPassword());
            clientAccount.setLinkMan(operator.getLinkMan());
            clientAccount.setMobilePhone(operator.getMobile());
            clientAccount.setTel(operator.getTel());
            clientAccount.setCompanyName(operator.getCompanyName());
            clientAccount.setHomePage(operator.getHomePage());
            clientAccount.setAddress(operator.getAddress());
            clientAccount.setEmail(operator.getEmail());
            clientAccount.setZip(operator.getZip());
            clientAccount.setBank(operator.getBank());
            clientAccount.setBankAccount(operator.getAccount());
            clientAccount.setBankAccountName(operator.getAccountName());
            clientAccount.setOperatorId(operator.getId());
            clientAccount.setStatus(Integer.parseInt(account.getState()));
        }
        List<Resources> resources = resourcesService.findAllResourcesByAccountId(accountId);
        //查询resourceId，拼接字符长，逗号分隔（a1,a2,...,an）
        if (resources.size() > 0) {//resources<=0说明没有添加权限信息
            for (int i = 0; i < resources.size() - 1; i++) {
                //循环取出resources中的id
                authority = authority + resources.get(i).getId().toString() + ",";
            }
            authority = authority + resources.get(resources.size() - 1).getId().toString();
        }
        model.addAttribute("clientAccount", clientAccount);
        model.addAttribute("getPower", authority);
        return page("edit");
    }

    /**
     * 创建客户端账户保存方法：要创建账号，广告主代理商或运营商，用角色关联权限
     * 
     * @param ca
     * @param ensueensurePassword
     * @return 
     *         注意：1.区分是添加保存还是修改保存（根据前台是否有ID传过来）；2.区分是创建运营商账号还是广告主代理账号(根据sys_type来区分
     *         )
     */
    @RequestMapping("/save")
    public String save(@ModelAttribute("form") ClientAccount ca,
                       @RequestParam(value = "ensurePassword", defaultValue = "") String ensueensurePassword,
                       @RequestParam(value = "power", defaultValue = "") String power, HttpServletRequest request) {
        String password = ca.getPassword();
        if (ca.getId() == null) {//新增客户账号
            ca.setPassword(Md5Tool.getMd5(password));

            //新增客户端账号，媒体和代理商都可以，有差别的后面更新（adminId）
            Account account = new Account();
            account.setAccountName(ca.getAccountName());
            account.setPassword(ca.getPassword());
            account.setType(ca.getType());
            account.setRealName(ca.getLinkMan());
            account.setTel(ca.getTel());
            account.setDescription(ca.getCompanyName());
            account.setState(ca.getStatus().toString());
            account.setCreateTime(new Date());
            account.setSysType(ca.getSysType());
            accountService.insertAccount(account);
            if (ca.getSysType() == 2) {//添加媒体
                //添加媒体
                Operator o = new Operator();
                o.setCompanyName(ca.getCompanyName());
                o.setLinkMan(ca.getLinkMan());
                o.setTel(ca.getTel());
                o.setMobile(ca.getMobilePhone());
                o.setAccount(ca.getBankAccount());
                o.setHomePage(ca.getHomePage());
                o.setAccountName(ca.getBankAccountName());
                o.setBank(ca.getBank());
                o.setAddress(ca.getAddress());
                o.setZip(ca.getZip());
                o.setEmail(ca.getEmail());
                o.setStatus(0);//开启
                o.setSupdated(new Date());
                o.setAdminId(account.getId());
                operatorService.add(o);
                //将运营商ID放入账户中
                Account acc = new Account();
                acc.setId(account.getId());
                acc.setOperatorId(o.getId());
                accountService.updateAccount(acc);
                //给账号分配角色
                if (!"".equals(power)) {//解析从前端传回的power字符串，里面如果缺少对应的角色的权限，封装入exceptRes
                    List<Long> rolesRes = roleService.findAllResIdByRole("9");//媒体角色的ID是9___这里要注意角色ID不能随便修改
                    String[] powers = power.split(",");
                    ArrayList<Long> intpower = new ArrayList<Long>();
                    for (int i = 0; i < powers.length; i++) {
                        if (!"".equals(powers[i])) {
                            intpower.add(Long.valueOf(powers[i]));
                        }
                    }
                    List<Long> exceptRes = new ArrayList<Long>();
                    for (int i = 0; i < rolesRes.size(); i++) {
                        if (intpower.contains(rolesRes.get(i))) {
                            continue;
                        } else {
                            exceptRes.add(rolesRes.get(i));
                        }
                    }
                    resourcesService.addAccountNotinResourcess(new Long(account.getId()), exceptRes);
                }
                RoleAccount ra = new RoleAccount();//给客户账号分配媒体角色  角色ID=9
                ra.setAccountId(account.getId());
                ra.setRoleId(9);
                roleService.addAccRole(ra);
            }
            if (ca.getSysType() == 3) {//添加代理商
                //添加代理商
                AdvAgent advAgent = new AdvAgent();
                advAgent.setName(ca.getCompanyName());
                advAgent.setContacts(ca.getLinkMan());
                advAgent.setTel(ca.getTel());
                advAgent.setMobile(ca.getMobilePhone());
                advAgent.setHomePage(ca.getHomePage());
                advAgent.setAddress(ca.getAddress());
                advAgent.setZip(ca.getZip());
                advAgent.setEmail(ca.getEmail());
                advAgent.setTitle(ca.getTitle());
                advAgent.setStatus(0);
                advAgent.setAdminId(account.getId());
                advAgentService.add(advAgent);
                //将代理商ID放入账户中
                Account acc = new Account();
                acc.setId(account.getId());
                acc.setAgentId(advAgent.getId());
                accountService.updateAccount(acc);

                //分配角色
                //给账号分配角色
                if (!"".equals(power)) {//解析从前端传回的power字符串，里面如果缺少对应的角色的权限，封装入exceptRes
                    List<Long> rolesRes = roleService.findAllResIdByRole("7");//代理商角色的ID是9___这里要注意角色ID不能随便修改
                    String[] powers = power.split(",");
                    ArrayList<Long> intpower = new ArrayList<Long>();
                    for (int i = 0; i < powers.length; i++) {
                        if (!"".equals(powers[i])) {
                            intpower.add(Long.valueOf(powers[i]));
                        }
                    }
                    List<Long> exceptRes = new ArrayList<Long>();
                    for (int i = 0; i < rolesRes.size(); i++) {
                        if (intpower.contains(rolesRes.get(i))) {
                            continue;
                        } else {
                            exceptRes.add(rolesRes.get(i));
                        }
                    }
                    resourcesService.addAccountNotinResourcess(new Long(account.getId()), exceptRes);
                }
                RoleAccount ra = new RoleAccount();//给客户账号分配代理商角色 角色ID=7
                ra.setAccountId(account.getId());
                ra.setRoleId(7);
                roleService.addAccRole(ra);
            }
        } else {//修改客户端账号信息
                //是否修改密码
            if (password != null) {
                ca.setPassword(Md5Tool.getMd5(password));
            }
            if (ca.getSysType() == 2) {//媒体信息修改
                //修改运营商信息
                Operator o = new Operator();
                o.setId(ca.getOperatorId());
                o.setLinkMan(ca.getLinkMan());
                o.setTel(ca.getTel());
                o.setMobile(ca.getMobilePhone());
                o.setCompanyName(ca.getCompanyName());
                o.setHomePage(ca.getHomePage());
                o.setAddress(ca.getAddress());
                o.setZip(ca.getZip());
                o.setEmail(ca.getEmail());
                o.setBank(ca.getBank());
                o.setAccountName(ca.getBankAccountName());
                //修改运营商账号信息
                Account account = new Account();
                account.setId(ca.getId());
                if (password != null) {
                    account.setPassword(ca.getPassword());
                }
                account.setState(ca.getStatus().toString());
                accountService.updateAccount(account);

                //更改权限
                if (!"".equals(power) || power != null) {//解析从前端传回的power字符串，里面如果缺少对应的角色的权限，封装入exceptRes
                    List<Long> rolesRes = roleService.findAllResIdByRole(9l);
                    String[] powers = power.split(",");
                    ArrayList<Long> intpower = new ArrayList<Long>();
                    for (int i = 0; i < powers.length; i++) {
                        if (!"".equals(powers[i])) {
                            intpower.add(Long.valueOf(powers[i]));
                        }
                        //	intpower.add(Long.valueOf(powers[i]));
                    }

                    //记录删除的权限
                    List<Long> exceptRes = new ArrayList<Long>();
                    for (int i = 0; i < rolesRes.size(); i++) {
                        if (intpower.contains(rolesRes.get(i))) {
                            continue;
                        } else {
                            exceptRes.add(rolesRes.get(i));
                        }
                    }
                    resourcesService.addAccountNotinResourcess(new Long(account.getId()), exceptRes);
                }
            }
            if (ca.getSysType() == 3) {//代理商信息修改
                //修改代理商信息
                AdvAgent advAgent = new AdvAgent();
                advAgent.setId(ca.getAgentId());
                advAgent.setAddress(ca.getAddress());
                advAgent.setContacts(ca.getLinkMan());
                advAgent.setEmail(ca.getEmail());
                advAgent.setHomePage(ca.getHomePage());
                advAgent.setMobile(ca.getMobilePhone());
                advAgent.setName(ca.getCompanyName());
                advAgent.setStatus(ca.getStatus());
                advAgent.setTel(ca.getTel());
                advAgent.setTitle(ca.getTitle());
                advAgent.setZip(ca.getZip());
                advAgent.setUpdated(new Date());
                advAgentService.edit(advAgent);
                //修改代理商账号信息
                Account account = new Account();
                account.setId(ca.getId());
                if (password != null) {
                    account.setPassword(ca.getPassword());
                }
                account.setState(ca.getStatus().toString());
                accountService.updateAccount(account);
                //更改权限
                if (!"".equals(power) || power != null) {//解析从前端传回的power字符串，里面如果缺少对应的角色的权限，封装入exceptRes
                    List<Long> rolesRes = roleService.findAllResIdByRole(7l);
                    String[] powers = power.split(",");
                    ArrayList<Long> intpower = new ArrayList<Long>();
                    for (int i = 0; i < powers.length; i++) {
                        //intpower.add(Long.valueOf(powers[i]));
                        if (!"".equals(powers[i])) {
                            intpower.add(Long.valueOf(powers[i]));
                        }
                    }

                    //记录删除的权限
                    List<Long> exceptRes = new ArrayList<Long>();
                    for (int i = 0; i < rolesRes.size(); i++) {
                        if (intpower.contains(rolesRes.get(i))) {
                            continue;
                        } else {
                            exceptRes.add(rolesRes.get(i));
                        }
                    }
                    resourcesService.addAccountNotinResourcess(new Long(account.getId()), exceptRes);
                }
            }
        }
        return redirect(page("list"));
    }

    /**
     * 开启 单个或者批量启用功能。 后面要做登录检验的，如果是主账号登录直接检查是否被停用。 权限管理：1（开启），0（停止） disable(1),
     * enable(0),
     * 
     * @param id
     * @return
     */
    @RequestMapping("enable")
    @ResponseBody
    public String enable(Long[] id) {
        if (ArrayUtils.isNotEmpty(id)) {
            accountService.updateState(LangUtil.array2List(id), Status.disable.value);
        }
        return OK;
    }

    /**
     * 暂停 单个或者批量禁用功能。 权限管理：1（开启），0（停止） disable(1), enable(0),
     * 
     * @param id
     * @return
     */
    @RequestMapping("disable")
    @ResponseBody
    public String disable(Long[] id) {
        if (ArrayUtils.isNotEmpty(id)) {
            accountService.updateState(LangUtil.array2List(id), Status.enable.value);
        }
        return OK;
    }

    /**
     * 判断账户名是否存在
     * 
     * @param model
     * @param clientAccountName
     * @return
     */
    @RequestMapping("isExist")
    @ResponseBody
    public String isExist(Model model, @RequestParam(defaultValue = "") String clientAccountName) {
        String success = "";
        Account account = accountService.querySingleAccount(clientAccountName);
        if (account != null) {
            model.addAttribute("isExist", new Long(1));
            success = "YES";
        } else {
            model.addAttribute("isExist", new Long(0));
            success = "NO";
        }
        return success;
    }

    //获取角色对应权限
    @RequestMapping("getRoleResource")
    public @ResponseBody List<Resources> getRoleResource(@RequestParam Long roleId) {
        List<Resources> roleResources = accountService.findRolesResources(roleId);
        return roleResources;
    }

    /**
     * 打开关联列表页
     * 
     * @param model
     * @return
     */
    @RequestMapping("/correlation")
    public String correlation(Model model, @RequestParam(defaultValue = "1") int page) {
        int totalRow = correlationService.countAllCorrelation();
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<Correlation> correlations = correlationService.findAllCorrelation(pager);
        model.addAttribute("pager", pager);
        model.addAttribute("correlations", correlations);
        return page("correlation");
    }

    /**
     * 创建关联
     * 
     * @return
     */
    @RequestMapping("createcorrelation")
    public String createCorrelation() {
        return page("createcorrelation");
    }

    /**
     * 取消关联
     * 
     * @return
     */
    @RequestMapping("cancelcorrelation")
    public String cancelCorrelation(@RequestParam Long agentId, @RequestParam Long operatorId) {
        Correlation ca = new Correlation();
        ca.setAgentId(agentId);
        ca.setOperatorId(operatorId);
        correlationService.deleteCorrelation(ca);
        return redirect(page("correlation"));
    }

    /**
     * 保存关联
     * 
     * @return
     */
    @RequestMapping("savecorrelation")
    public String saveCorrelation(@ModelAttribute("form") Correlation ca) {
        correlationService.addCorrelation(ca);
        return redirect(page("correlation"));
    }

    /**
     * 查询是否 存在关联
     * 
     * @author CloudCross
     */
    @RequestMapping("is_exit")
    public @ResponseBody String isExitCorrelation(@RequestParam Long operatorId) {
        List<Correlation> co = correlationService.findCorrelationByOperatorId(operatorId);
        if (co.size() > 0) {
            return "YES";
        } else {
            return "NO";
        }
    }

    @RequestMapping("/exportDataReportExcel")
    public void exportDataReportExcel(HttpServletResponse response, @RequestParam(defaultValue = "0") Long sysType,
                                      String searchValue) {
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("sysTypeA", sysType);//用于excel导出

        if (sysType != null && sysType != 0) {
            condition.put("sysType", sysType);
        }
        if (StringUtils.isNotBlank(searchValue)) {
            condition.put("searchVal", "%" + searchValue + "%");
        }
        condition.put("searchValue", searchValue);
        List<ClientAccount> clientAccountsList = accountService.queryClientAccountByCondition(condition, null);
        //循环得到每个客户账号的最后登录时间！
        for (ClientAccount ca : clientAccountsList) {
            UserLogin login = userLoginService.queryUserLoginById(ca.getId());
            if (login == null) {
                continue;
            }
            ca.setLoginTime(login.getLoginTime());
        }
        condition.put("dataList", clientAccountsList);

        response.reset();
        // Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
        response.setContentType("application/vnd.ms-excel;charset=utf8");
        // 设置excel文件名称
        SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "clientAccount" + df2.format(new Date());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        // 需要对excel的列和行的总数进行指定
        int column = 10;
        condition.put("dataSize", (clientAccountsList.size() + 100));
        condition.put("column", column);

        condition.put("accountList", "客户账号列表");
        String excelTemplate = templateProcessor.processTemplate("excel/dataClientAccount.ftl", condition);
        try {
            PrintWriter out = response.getWriter();
            out.write(excelTemplate);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
